package org.spring.springboot.view;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.spring.springboot.domain.Area;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/7/2 10:50
 */
public class PdfView extends AbstractPdfView {

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // change the file name
        response.setHeader("Content-Disposition", "attachment; filename=\"my-pdf-file.pdf\"");

        List<Area> areas = (List<Area>) model.get("areas");
        document.add(new Paragraph("Generated Areas " + LocalDate.now()));

        PdfPTable table = new PdfPTable(areas.stream().findAny().get().getColumnCount());
        table.setWidthPercentage(100.0f);
        table.setSpacingBefore(10);

        // define font for table header row
        Font font = FontFactory.getFont(FontFactory.TIMES);
        font.setColor(BaseColor.WHITE);

        // define table header cell
        PdfPCell cell = new PdfPCell();
        cell.setBackgroundColor(BaseColor.DARK_GRAY);
        cell.setPadding(5);

        // write table header
        cell.setPhrase(new Phrase("provinceName", font));
        table.addCell(cell);

        cell.setPhrase(new Phrase("cityName", font));
        table.addCell(cell);

        cell.setPhrase(new Phrase("areaName", font));
        table.addCell(cell);

        cell.setPhrase(new Phrase("areaId", font));
        table.addCell(cell);

        for (Area area : areas) {
            table.addCell(area.getProvinceName());
            table.addCell(area.getCityName());
            table.addCell(area.getAreaName());
            table.addCell(area.getAreaId());
        }

        document.add(table);
    }
}
